import 'package:dio/dio.dart';
import 'package:fsharing/core/models/bank.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';

class BankUpdateModel extends ViewModel {
  final Api api;
  final Bank bank;

  MapEntry<String, dynamic> _type;
  String bankCardId;
  String cardOwnerName;
  String mainBankName;
  String bankName;
  bool _defaultAccount;

  String _errorMessage;

  BankUpdateModel(this.api, this.bank) : super() {
    if (bank != null) {
      _type = MapEntry(bank.accountType, bank.accountTypeName);
      bankCardId = bank.bankCardId;
      cardOwnerName = bank.cardOwnerName;
      mainBankName = bank.mainBankName;
      bankName = bank.bankName;
      _defaultAccount = bank.defaultAccount;
    }
  }

  MapEntry<String, dynamic> get type => _type;

  set type(MapEntry<String, dynamic> value) {
    _type = value;
    notifyListeners();
  }

  bool get defaultAccount => _defaultAccount;

  set defaultAccount(bool value) {
    _defaultAccount = value;
    notifyListeners();
  }

  String get errorMessage => _errorMessage;

  Future<ViewState> bankUpdate() async {
    viewState = ViewState.busy;
    try {
      var bank = Bank(
        this.bank?.id,
        _type?.key,
        _type?.value,
        bankCardId,
        cardOwnerName,
        mainBankName,
        bankName,
        defaultAccount,
      );
      await api.bankUpdate(bank);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
